import os
import sys
from pathlib import Path
from typing import Dict, Any, Optional
from dataclasses import dataclass
from utils.logger import logger


@dataclass
class DatabaseConfig:
    """数据库配置"""
    host: str = "localhost"
    port: int = 3306
    username: str = ""
    password: str = ""
    database: str = ""


@dataclass
class ApiConfig:
    """API配置"""
    timeout: int = 30
    retry_count: int = 3
    retry_delay: int = 1


class Settings:
    """配置管理类"""

    def __init__(self):
        self.env = os.getenv('ENV', 'dev').lower()
        self.project_root = Path(__file__).parent.parent
        self.config_data = self._load_config()
        self.db_config = DatabaseConfig()
        self.api_config = ApiConfig()

    def _load_config(self) -> Dict[str, Any]:
        """加载环境配置"""
        try:
            if self.env == 'dev':
                from config.environments.dev import CONFIG
            elif self.env == 'test':
                from config.environments.test import CONFIG
            elif self.env == 'pre':
                from config.environments.pre import CONFIG
            elif self.env == 'prod':
                from config.environments.prod import CONFIG
            else:
                logger.warning(f"未知环境: {self.env}, 使用默认开发环境")
                from config.environments.dev import CONFIG

            logger.info(f"成功加载 {self.env} 环境配置")
            return CONFIG

        except ImportError as e:
            logger.error(f"加载环境配置失败: {e}")
            raise RuntimeError(f"无法加载 {self.env} 环境配置")

    def get(self, key: str, default: Any = None) -> Any:
        """获取配置项"""
        keys = key.split('.')
        value = self.config_data

        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            if default is not None:
                return default
            logger.warning(f"配置项未找到: {key}")
            return None

    def get_account(self, account_type: str = 'admin') -> Dict[str, str]:
        """获取账号配置"""
        account_key = f"accounts.{account_type}"
        return self.get(account_key, {})

    def get_host(self, host_type: str = 'host') -> str:
        """获取主机地址"""
        return self.get(f'hosts.{host_type}', '')

    @property
    def current_env(self) -> str:
        """当前环境"""
        return self.env

    @property
    def is_production(self) -> bool:
        """是否为生产环境"""
        return self.env == 'prod'

    @property
    def is_development(self) -> bool:
        """是否为开发环境"""
        return self.env == 'dev'


# 全局配置实例
settings = Settings()


# 便捷函数
def get_config(key: str, default: Any = None) -> Any:
    """获取配置项"""
    return settings.get(key, default)


def get_account_config(account_type: str = 'admin') -> Dict[str, str]:
    """获取账号配置"""
    return settings.get_account(account_type)


def get_host_config(host_type: str = 'host') -> str:
    """获取主机配置"""
    return settings.get_host(host_type)